package breadbox.client.operations;

import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import breadbox.client.logging.Logger;
import breadbox.dataManagement.RMIMessage;
import breadbox.pastry.Message;

public class Delete extends Operation {
	private long[] ids = null;
	private RMIMessage rmiServer;
	
	public Delete(String f, RMIMessage rmiServer) {
		// check log for file, fail if not found
		Logger l = new Logger();
		try {
			this.ids = l.getIds(f);
		} catch (FileNotFoundException e) {
			System.err.println("Delete error: Unable to find file: " + f);
			return;
		}
		this.rmiServer = rmiServer;
		l.remove(f);
	}
	
	public List<Message> send() {
		List<Message> messages = new ArrayList<Message>();
		for (long id : ids) {
			messages.add(sendMessage(id));
		}
		return messages;
	}
	
	private Message sendMessage(long id) {
		Message m = new Message(id, OperationType.DELETE.toString(), null);
		try {
			rmiServer.sendMessage(m);
		} catch (RemoteException e) {
			System.err.println("Delete error: Cannot send delete message");
		}
		return m;
	}

}
